package com.deepseek.utils;

import org.json.JSONObject;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class StreamHttpRequest {

    public static HttpURLConnection conn = null;

    public static void GetAnswerOut(String jsonInput) {
        String targetUrl = "http://219.245.0.41:8000/v1/chat/completions";

        try {
            // 创建连接并发送请求
            URL url = new URL(targetUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);
            conn.setChunkedStreamingMode(1024); // 启用分块传输

            // 发送请求体
            try (OutputStream os = conn.getOutputStream()) {
                os.write(jsonInput.getBytes(StandardCharsets.UTF_8));
            }

            // 获取响应状态
            int status = conn.getResponseCode();
            System.out.println("\nHTTP Status Code: " + status + "\n");

            // 获取输入流（根据状态码选择正确流）
            InputStream inputStream = status >= 400 ? conn.getErrorStream() : conn.getInputStream();
            if (inputStream == null) {
                System.out.println("No response body received");
                return;
            }

            // 使用缓冲读取器实现流式输出
            try (InputStreamReader isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
                char[] buffer = new char[2048];
                int bytesRead;
                StringBuilder responseBuilder = new StringBuilder();

                // 实时输出循环
                while ((bytesRead = isr.read(buffer)) != -1) {
                    String data = new String(buffer, 0, bytesRead);
                    responseBuilder.append(data);
                    
                    // 处理每个数据块
                    String[] chunks = data.split("\n");
                    for (String chunk : chunks) {
                        if (chunk.startsWith("data: ")) {
                            try {
                                String jsonStr = chunk.substring(6).trim();
                                if (jsonStr.equals("[DONE]")) {
                                    continue;
                                }
                                
                                JSONObject jsonObject = new JSONObject(jsonStr);
                                if (jsonObject.has("choices") && jsonObject.getJSONArray("choices").length() > 0) {
                                    JSONObject choice = jsonObject.getJSONArray("choices").getJSONObject(0);
                                    if (choice.has("delta") && choice.getJSONObject("delta").has("content")) {
                                        String content = choice.getJSONObject("delta").getString("content");
                                        System.out.print(content);
                                        System.out.flush();
                                    }
                                }
                            } catch (Exception e) {
                                System.err.println("Error parsing chunk: " + chunk);
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
}